class Api::V1::RolesController < Api::V1::BaseController
  has_scope :power

  def index
    @roles = apply_scopes(Role).all
    @roles = paginate(@roles)
    render json: @roles, meta: paginate_meta(@roles)
  end

  def batch_create
    begin
      roles = []
      create_params[:attributes].each do |role|
        roles << Role.new(role)
      end

      Role.import! roles
      render status: :created
    rescue RecordInvalid
      render status: :forbidden
    rescue
      render status: :forbidden
    end
  end

  def create
    begin
      @role = Role.new(create_params[:attributes])
      authorize @role
      @role.save!
      render json: @role, status: 201
    rescue ActiveRecord::StatementInvalid
      @role.errors.add(:exec_error, '数据库错误，请联系管理员')
      error_render(@role, 403)
    rescue => err
      error_render(err.record, 403)
    end

  end

  private

  def create_params
    params.require(:data).permit(:type, :id, attributes: [:name, :privilege])
  end

end
